package org.mxp.utils;

import org.apache.commons.collections.MapUtils;
import org.mxp.wobsocket.WebSocketServer;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class ChatMessageUtil {

    /**
     * 喷射用户信息
     */
    private static ConcurrentHashMap<String, Boolean> sprayData = new ConcurrentHashMap<>();

    private LinkedBlockingQueue<Map<String, Object>> chatList = new LinkedBlockingQueue<>(100);

    public String getMsg(String chatStr) {
        if (chatStr != null) {
            String[] chatData = chatStr.split("※");
            if (chatData.length == 2) {
                return chatData[1];
            }
        }
        return "";
    }

    public void addChat(String chatStr) {
        if (chatStr != null) {
            String[] chatData = chatStr.split("※");
            if (chatData.length == 2) {
                // 当队列满时，移除队列头部元素，然后添加新元素
                if (chatList.remainingCapacity() == 0) {
                    chatList.poll();
                }
                chatList.offer(new HashMap<String, Object>() {{
                    put("userId", chatData[0]);
                    put("msg", chatData[1]);
                }});
            }
        }
    }

    public String getChatAll() {
        String result = "";
        for (Map<String, Object> tempMap: chatList) {
            result += MapUtils.getString(tempMap, "userId") + "※" + MapUtils.getString(tempMap, "msg") + "※※";
        }
        if (!result.isEmpty()) {
            result = result.substring(0, result.length() - 2);
        }
        return result;
    }

    /**
     * 切换喷射模式
     * @param userId
     */
    public void changeSpray(String userId) {
        Boolean b = sprayData.get(userId);
        if (b == null) {
            b = false;
        }
        sprayData.put(userId, !b);
    }

    /**
     * 获取喷射状态
     * @param userId
     * @return
     */
    public boolean getSpray(String userId) {
        Boolean b = sprayData.get(userId);
        if (b == null) {
            b = false;
        }
        return b;
    }

    /**
     * 删除喷射用户
     * @param userId
     */
    public void removeSprayUser(String userId) {
        sprayData.remove(userId);
    }
}
